package shinesend.com.cn.anscyhandledemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by MyPC on 2016/11/22.
 */
public class AsyncActivity extends Activity{

    private ProgressBar progressbar;
    private ImageView imageview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        imageview = (ImageView) findViewById(R.id.imageview);
    }

    public void click(View view) {
        String url = "http://pic22.nipic.com/20120725/6573765_165852471000_2.jpg";
        new MyAsync().execute(url);
    }

    //异步请求处里的使用;
    /**
     * String 传递的参数  在子线程中完成; 也就是耗时操作;
     * ,Integer, 进度值   在主线程完成;
     * String 返回的数据; 子线程;
     */
    class MyAsync extends AsyncTask<String ,Integer, String > {
        OutputStream os;
        InputStream is;
        @Override//主子线程中完成;主要用于网络操作和耗时操作;
        protected String doInBackground(String... params) {
            String filename = getFileOnSdcard("tmp"+ System.currentTimeMillis());
            int total = 0;
            int byteCount = 0;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setRequestMethod("GET");
                if (huc.getResponseCode()==HttpURLConnection.HTTP_OK){
                    File file = new File(filename);
                    if (!file.exists()){
                        file.createNewFile();
                    }
                     is= huc.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    //把流输入到指定的文件中去;
                     os= new FileOutputStream(filename);
                    byte[] bytes = new byte[1024];
                    byteCount = huc.getContentLength();
                    int len = 0 ;
                    while ((len =is.read(bytes))!=-1){
                        //调用传递进度的方法;
                        total +=len;
                        Log.e("=========",""+(total*100/byteCount));
                        publishProgress(total*100/byteCount);
                        os.write(bytes,0,len);
                    }
                    //注意必须把is在写在outStream里之前
                    Log.e(",,,,,",""+(bitmap==null));
                }
            }  catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    os.flush();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
          return filename;
        }
        //更新进度的方法;在主线程中运行;
        @Override
        protected void onProgressUpdate(Integer... values) {
           // super.onProgressUpdate(values);
            Log.e("-----------",">>>>>>>>>>>"+values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            Log.e("----------->>>",""+(s==null));
            imageview.setImageBitmap(scaledPicture(s));
        }
    }
    private String getFileOnSdcard(String s) {
        String base = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            base = (Environment.getExternalStorageDirectory().getAbsolutePath());
        } else {
            base = Environment.getDownloadCacheDirectory().toString();
        }
        base+="/"+s;
        return base;
    }

    //图片压缩方法;

    /**
     * 图片压缩的方法;
     * @param s 图片的路径;
     * @return bitmap;
     */
    private Bitmap scaledPicture(String s){
        File file = new File(s);
        Log.e("-------------","文件是否存在;"+file.exists());
        BitmapFactory.Options options = new BitmapFactory.Options();
        int scale = 1;
       // options.inJustDecodeBounds = true;//只读取边界,不读内容;
        options.inPreferredConfig= Bitmap.Config.ARGB_8888;//设置读取文件的格式\
        Bitmap bitmap = null;
//               bitmap =  BitmapFactory.decodeFile(s,options);
//        int w = options.outWidth;
//        //屏幕的宽度
//        int mxaW = getResources().getDisplayMetrics().widthPixels;
//        if (mxaW<w){
//            scale = w/mxaW;
//        }
//        if (scale<1){
//            scale = 1;//不用压缩了;
//        }
        //压缩图片的比例;
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(s,options);
        return bitmap;
    }
}
